﻿using KeDa2025_.Utils;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.UI.WebControls;
using System.Net;

namespace KeDa2025_
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["User"] != null)
                {
                    InitStudent();
                }
                else
                {
                    Response.Write("<script>alert('请先登录!');window.location.href='denglu.aspx'</script>");
                }
            }
        }

        private void InitStudent()
        {

            //创建数据库链接
            string sql = "SELECT n.*, u.account FROM notes n INNER JOIN users u ON u.id = n.user_id";
            //string sql = ("select n.*,u.account from dbo.notes n inner join users u on u.id=n.user_id");
            MySqlConnection connection = new MySqlConnection("server=localhost;user id=zmy2;password=zmy20020525;database=forum;");
            MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter(sql, connection);
            DataSet ds = new DataSet();
            //填充容器
            sqlDataAdapter.Fill(ds);
            //把容器给repeater
            rpUser.DataSource = ds;
            rpUser.DataBind();
        }

        public string InitUser()
        {
            if (Session["User"] == null)
                return "";
            DataRow userRow = (DataRow)Session["User"];
            string genderText = userRow["gender"].ToString() == "0" ? "男" : "女";
            // 获取用户所在城市的天气信息
            string city = userRow["name"].ToString(); // 从用户信息中获取城市
            string url = "http://gfeljm.tianqiapi.com/api?unescape=1&version=v61&appid=87127221&appsecret=8VKWP1MH&city=" + city.Replace("市", "");
            WebClient client = new WebClient();//实例化一个远程访问类
            byte[] byteResult = client.DownloadData(url);//使用访问类，请求接口，并将接口内容解析为字符串
            string result = Encoding.UTF8.GetString(byteResult);//Json
                                                                //借用第三方序列化反序列化第三方库Newtonsoft
            JObject obj = (JObject)JsonConvert.DeserializeObject(result);//  将Json字符串反序列化为一个newtonsoft提供的一个对象
                                                                         //取你要的内容         
                                                                         // 获取天气信息
            string weather = obj["wea"].ToString(); // 当前天气
            string currentTemp = obj["tem"].ToString(); // 当前温度
            string maxTemp = obj["tem1"].ToString(); // 最高温度
            string minTemp = obj["tem2"].ToString(); // 最低温度

            //登录人信息
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("<div class=\"segment left\">");
            stringBuilder.Append("<i class=\" glyphicon glyphicon-user left\"></i>");
            stringBuilder.Append($"     <h3 class=\"left\">欢迎{userRow["account"]}登录<br>");
            stringBuilder.Append("  <span>管理这个设备及其传感器</span>");
            stringBuilder.Append("  </h3>");
            stringBuilder.Append(" </div>");
            stringBuilder.Append("<div class=\"clear\"></div>");
            stringBuilder.Append("  <div class=\"segment2\">");
            stringBuilder.Append("  <div class=\"user_left\">");
            stringBuilder.Append($"  <img width=\"160\" height=\"160\" src=\"{userRow["img_url"]}\">");
            stringBuilder.Append("  </div>");
            stringBuilder.Append(" <div class=\"user_right\">");
            stringBuilder.Append($"<h5>你好：{userRow["account"]}<br>");
            stringBuilder.Append($" <span><i class=\"glyphicon glyphicon-time\"></i>&nbsp;{DateTime.Now}</span>");
            stringBuilder.Append("    </h5>");
            stringBuilder.Append("<p>");
            stringBuilder.Append($"  所在地:{userRow["name"]}<br>");
            stringBuilder.Append($"性别:{genderText}<br>");
            stringBuilder.Append($"  QQ:{userRow["qq"]}<br>");
            stringBuilder.Append($"    邮箱：{userRow["email"]}");
            stringBuilder.Append("  </p>");
            stringBuilder.Append($"天气: {weather}; 当前温度: {currentTemp}℃; 最高温度: {maxTemp}℃; 最低温度: {minTemp}℃");
            stringBuilder.Append("</div>");
            stringBuilder.Append("</div>");
            return stringBuilder.ToString();


        }


        protected void rpUser_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            #region 删除权限
            //获取当前行的发布人
            int userId = Convert.ToInt32((e.Item.FindControl("hfUserId") as HiddenField).Value);
            DataRow loginUser = (DataRow)Session["User"];

            // 检查并获取当前登录人权限
            int loginUserManager = DBNull.Value.Equals(loginUser["manager"]) ? 0 : Convert.ToInt32(loginUser["manager"]);

            // 检查并获取当前登录人 ID
            int loginUserId = DBNull.Value.Equals(loginUser["id"]) ? 0 : Convert.ToInt32(loginUser["id"]);

            //获取当前登录人权限
            //int loginUserManager = Convert.ToInt32(loginUser["manager"]);
            //int loginUserId = Convert.ToInt32(loginUser["id"]);
            //判断登录人是不是日志发布人或者管理员
            //是:不处理
            //不是:删除隐藏
            if (loginUserManager != 1 && loginUserId != userId)
            {
                e.Item.FindControl("LinkButton1").Visible = false;
                e.Item.FindControl("cbxItem").Visible = false;
            }
            #endregion
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            #region 全选删除
            int sign = 0;
            //遍历所有的数据行
            for (int i = 0; i < rpUser.Items.Count; i++)
            {
                //获取每一行的勾选框
                CheckBox cbx = rpUser.Items[i].FindControl("cbxItem") as CheckBox;
                int noteId = Convert.ToInt32((rpUser.Items[i].FindControl("hfNoteId") as HiddenField).Value);
                //判断勾选框是否勾选
                if (cbx.Checked == true)
                {

                    string sql = string.Format("delete from notes where id=" + noteId);
                    MySqlConnection connection = new MySqlConnection("server=localhost;user id=zmy2;password=zmy20020525;database=forum;");
                    MySqlCommand cmd = new MySqlCommand(sql, connection);
                    connection.Open();
                    int flag = cmd.ExecuteNonQuery();
                    connection.Close();

                    if (flag > 0)
                    {
                        sign++;
                    }
                }
            }
            if (sign > 0)
                Response.Write($"<script>alert('删除成功，共删除{sign}条')</script>");
            InitStudent();

            #endregion
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {

            try
            {
                // 获取 LinkButton 控件
                LinkButton linkButton = (LinkButton)sender;

                // 获取 CommandArgument 中的 NoteId
                int noteId = Convert.ToInt32(linkButton.CommandArgument);

                // 执行删除操作
                string connectionString = "server=localhost;user id=zmy2;password=zmy20020525;database=forum;";
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    // 删除语句
                    string sql = "DELETE FROM notes WHERE id = @NoteId";
                    MySqlCommand cmd = new MySqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("@NoteId", noteId);

                    // 打开连接
                    conn.Open();

                    // 执行删除操作
                    int result = cmd.ExecuteNonQuery();

                    // 关闭连接
                    conn.Close();

                    if (result > 0)
                    {
                        // 删除成功，提示用户并刷新页面
                        Response.Write("<script>alert('删除成功');</script>");
                        // 刷新当前页面
                        Response.Redirect(Request.Url.ToString());
                    }
                    else
                    {
                        // 删除失败，提示用户
                        Response.Write("<script>alert('删除失败');</script>");
                    }
                }
            }
            catch (Exception ex)
            {
                // 捕获异常并显示错误信息
                Response.Write("<script>alert('错误: " + ex.Message + "');</script>");
            }
        }
    }
}
